package org.example.business.endpoint.http.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.example.business.endpoint.http.HttpServer;
import org.example.objevent.executor.EventExecutor;
import org.example.objevent.executor.EventExecutorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class NettyHttpServer implements HttpServer{

    @Autowired
    private EventExecutor executor;

    @Autowired
    private EventExecutorFactory executorFactory;

    @Autowired
    private ChannelHandler handler;

    @Value("${server.http.host:0.0.0.0}")
    private String host;

    @Value("${server.http.port:8080}")
    private int port;

    @Override
    public void startup(){

        try{

            NioEventLoopGroup bossGroup = new NioEventLoopGroup(executorFactory);
            NioEventLoopGroup workerGroup = new NioEventLoopGroup(executorFactory);

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(handler);

            serverBootstrap.bind(host, port);

            log.info("http waiting on {}:{} ....", host, port);

        }catch (Throwable e){
            log.error("", e);

        }

    }

    @Override
    public void shutdown(){
        System.exit(0);

    }

}
